package appServer

import (
	"github.com/gin-gonic/gin"
	"io/fs"
	"io/ioutil"
	"log"
	"main/src/apps"
	"main/src/apps/contentManage"
	"main/src/apps/logManage"
	"main/src/apps/siteManage"
	"main/src/apps/skipManage"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

func Exists(path string) bool {
	_, err := os.Stat(path) //os.Stat获取文件信息
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return true
}

func isHas(files []fs.FileInfo, s string) (res bool) {
	res = false
	for _, file := range files {
		if file.Name() == s {
			res = true
			break
		}
	}
	return res
}

func GetContentAppView(c *gin.Context) {
	agent := c.GetHeader("User-Agent")
	body := &GetContentDto{}
	err := c.ShouldBindQuery(&body)
	if err != nil {
		return
	}
	log.Println(body)
	if strings.Contains(agent, "Googlebot") {
		// 是Google蜘蛛访问
		//var filename = c.Request.URL.RawQuery
		//
		//if filename[:5] != ".html" {
		//	filename += ".html"
		//}
		//var filepath = "../temps/" + filename
		//// 判断文件是否存在
		//if Exists(filepath) {
		//	file, e := os.ReadFile(filepath)
		//	if e != nil {
		//		fmt.Println(e.Error())
		//	}
		//
		//	c.Header("Content-Type", "text/html; charset=utf-8")
		//	c.String(http.StatusOK, string(file))
		//	return
		//}
		cat := skipManage.Cat{
			Id: body.CatId,
		}

		apps.DB.Debug().Where("id = " + strconv.Itoa(cat.Id)).First(&cat)
		var content []contentManage.Content
		apps.DB.Debug().Select("id").Where("cat = " + strconv.Itoa(cat.Id)).Order("RAND()").Limit(2).Find(&content)
		for instance := range content {
			files, _ := ioutil.ReadDir("./contents")
			filename := strconv.Itoa(content[instance].Id) + ".txt"
			if isHas(files, filename) {
				contentByte, _ := ioutil.ReadFile("./contents/" + filename)
				content[instance].Article = string(contentByte)
			} else {
				apps.DB.Debug().Where("id = " + strconv.Itoa(content[instance].Id)).First(&content[instance])
				file, _ := os.OpenFile("./contents/"+filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0777)
				file.WriteString(content[instance].Article)

				defer file.Close()
			}
		}
		var keywords []contentManage.KeyWord
		var k_s []string
		var s_k_s []string
		apps.DB.Debug().Where("cat = " + strconv.Itoa(cat.Id)).Order("RAND()").Limit(11).Find(&keywords)
		for i := range keywords {
			if len(keywords) >= (i + 1) {
				k_s = append(k_s, keywords[i].Text)
				s_k_s = append(s_k_s, strings.ReplaceAll(keywords[i].Text, " ", "-"))
			} else {
				k_s = append(k_s, body.Keyword)
				s_k_s = append(s_k_s, strings.ReplaceAll(body.Keyword, " ", "-"))
			}

		}
		images := contentManage.Image{}
		apps.DB.Debug().Where("cat = " + strconv.Itoa(cat.Id)).Order("RAND()").First(&images)
		var links []siteManage.Domain
		var l_s = []string{}
		var self_links []siteManage.Domain
		var self_l_s = []string{}

		apps.DB.Debug().Where("url not like '@self_link@%'").Order("RAND()").Limit(5).Find(&links)
		apps.DB.Debug().Where("url like '@self_link@%'").Order("RAND()").Limit(5).Find(&self_links)
		for i := range links {
			l_s = append(l_s, links[i].URL)
		}
		for i := range self_links {
			self_l_s = append(self_l_s, strings.ReplaceAll(self_links[i].URL, "@self_link@", ""))
		}

		data := &ContentToClientDto{
			Id:           0,
			Article:      content,
			ReqKeyword:   strings.ReplaceAll(body.Keyword, "-", " "),
			Image:        images.URL,
			Keyword:      k_s,
			SpaceKeyword: s_k_s,
			Links:        l_s,
			SelfLinks:    self_l_s,
		}
		var dataMap = map[string]interface{}{
			"data":        data,
			"neilinks":    s_k_s[5:10],
			"title1":      strings.ReplaceAll(data.Keyword[0], "-", " "),
			"title2":      data.Keyword[1],
			"kw":          k_s,
			"kw2":         k_s[5:10],
			"wailinks":    data.Links,
			"time":        time.Now().Format(time.DateTime),
			"a1":          content[0].Article,
			"a2":          content[1].Article,
			"center_kw_s": strings.ReplaceAll(keywords[10].Text, " ", "-"),
			"center_kw":   keywords[10].Text,
		}
		if body.Template == "" {
			body.Template = "mb"
		}
		files, _ := ioutil.ReadDir("./templates")
		if !isHas(files, body.Template+".html") {
			body.Template = "mb"
		}
		c.HTML(http.StatusOK, body.Template+".html", dataMap)
		//var b = []byte{}
		//var buf = bytes.NewBuffer(b)
		//t, _ := template.ParseFiles("./templates/mb.html")
		//_ = t.Execute(buf, dataMap)
		//
		//file, _ := os.OpenFile(filepath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0777)
		//file.Write(buf.Bytes())
		//defer file.Close()
	} else {
		// 不是Google蜘蛛访问
		var skip = skipManage.Skip{
			Id: body.SkipId,
		}
		apps.DB.Where("id = " + strconv.Itoa(body.SkipId)).First(&skip)
		log.Println(skip.URL)
		http.Redirect(c.Writer, c.Request, skip.URL, http.StatusSeeOther)
	}
}

func GetAllDomainView(c *gin.Context) {

	var domain []siteManage.Domain

	apps.DB.Find(&domain)

	c.HTML(http.StatusOK, "allDomain.html", map[string]interface{}{
		"link": domain,
	})
}

func CreateLogAppView(c *gin.Context) {
	logManage.CreateLog(c)
}
